package com.spring.framework.config.async.annotation;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xuweizhi
 */
@Component
public class MyAsyncConfigurer implements AsyncConfigurer {

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new AsyncUncaughtExceptionHandler() {
			/**
			 * 自定义异常处理逻辑
			 * @param ex 抛出的异常
			 * @param method 抛出异常的方法
			 * @param params 抛出异常的方法参数
			 */
			@Override
			public void handleUncaughtException(Throwable ex, Method method, Object... params) {
				System.out.println("-----自定义异常处理-------");
				System.out.println(method.getName());
				System.out.println(ex.getMessage());
				System.out.println(Arrays.toString(params));
				System.out.println("-----自定义异常处理-------");
			}
		};
	}

	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		//配置核心线程数
		executor.setCorePoolSize(5);
		//配置最大线程数
		executor.setMaxPoolSize(10);
		//配置队列大小
		executor.setQueueCapacity(800);
		//配置线程池中的线程的名称前缀
		executor.setThreadNamePrefix("myAsyncConfigurer-");
		// rejection-policy：拒绝策略，由调用者所在的线程来执行
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		/*
		 * 注意，这里配置的ThreadPoolTaskExecutor不会被Spring管理，因此需要手动initialize初始化
		 */
		executor.initialize();
		return executor;
	}
}
